package com.qst.task;

import com.qst.pojo.entity.SystemSettings;
import com.qst.repository.SystemSettingsRepository;
import com.qst.service.InventoryMonitorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * 库存检查定时任务
 */
@Component
public class InventoryCheckTask {

    private static final Logger logger = LoggerFactory.getLogger(InventoryCheckTask.class);

    @Autowired
    private InventoryMonitorService inventoryMonitorService;

    @Autowired
    private SystemSettingsRepository settingsRepository;

    /**
     * 每小时执行一次库存检查（默认频率）
     * 如果设置为hourly，则执行检查
     */
    @Scheduled(cron = "0 0 * * * ?") // 每小时的整点执行
    public void hourlyInventoryCheck() {
        try {
            String frequency = getCheckFrequency();
            
            if ("hourly".equals(frequency)) {
                inventoryMonitorService.checkAllStationsInventory();
            }
        } catch (Exception e) {
            logger.error("每小时库存检查任务执行失败", e);
        }
    }

    /**
     * 每天执行一次库存检查
     * 如果设置为daily，则执行检查
     */
    @Scheduled(cron = "0 0 9 * * ?") // 每天上午9点执行
    public void dailyInventoryCheck() {
        try {
            String frequency = getCheckFrequency();
            
            if ("daily".equals(frequency)) {
                inventoryMonitorService.checkAllStationsInventory();
            }
        } catch (Exception e) {
            logger.error("每日库存检查任务执行失败", e);
        }
    }

    /**
     * 每周执行一次库存检查
     * 如果设置为weekly，则执行检查
     */
    @Scheduled(cron = "0 0 9 * * MON") // 每周一上午9点执行
    public void weeklyInventoryCheck() {
        try {
            String frequency = getCheckFrequency();
            
            if ("weekly".equals(frequency)) {
                inventoryMonitorService.checkAllStationsInventory();
            }
        } catch (Exception e) {
            logger.error("每周库存检查任务执行失败", e);
        }
    }

    /**
     * 实时检查（每5分钟执行一次）
     * 如果设置为realtime，则执行检查
     */
    @Scheduled(cron = "0 */5 * * * ?") // 每5分钟执行一次
    public void realtimeInventoryCheck() {
        try {
            String frequency = getCheckFrequency();
            
            if ("realtime".equals(frequency)) {
                inventoryMonitorService.checkAllStationsInventory();
            }
        } catch (Exception e) {
            logger.error("实时库存检查任务执行失败", e);
        }
    }

    /**
     * 获取库存检查频率配置
     */
    private String getCheckFrequency() {
        Optional<SystemSettings> setting = settingsRepository.findBySettingKey("inventory.checkFrequency");
        return setting.map(SystemSettings::getSettingValue).orElse("hourly");
    }
}

